package com.delu.filter;

import com.alibaba.fastjson.JSONObject;
import com.delu.data.Result;
import com.delu.em.ResultEnum;
import com.google.common.util.concurrent.RateLimiter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//表示网关限流
@Component
public class RequestFilter extends ZuulFilter {
    //每秒产生3个令牌(一般情况下我们的项目就是每秒产生1000到2000的并发)
    private static final RateLimiter RATE_LIMITER = RateLimiter.create(3);

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return -1;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //获取请求上下文
        RequestContext requestContext = RequestContext.getCurrentContext();
        System.out.println("获取令牌");
        //尝试获取令牌
        boolean tryAcquire = RATE_LIMITER.tryAcquire();
        // 如果获取不到就直接停止
        if(!tryAcquire){
            System.out.println("没有获取到令牌");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            HttpServletResponse response = requestContext.getResponse();
            try {
                response.setContentType("text/html;charset=utf-8");
                Result response1 = Result.response(ResultEnum.TOO_MANY_REQUESTS);
                response.getWriter().write(JSONObject.toJSONString(response1));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
